<template>
  <div class="app-container">
    <div class="header">
      <UserAcatar @transfer="change" />
    </div>
    <div class="filter-container" style="margin-bottom: 20px">
      <el-input
        v-model="listQuery.title"
        placeholder="标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="提交人数" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.publish_number }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="发布时间">
        <template slot-scope="scope">
          <span>{{ scope.row.publish_time }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="作者">
        <template slot-scope="scope">
          <span>{{ scope.row.teacher_name }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" align="center" label="课程名称">
        <template slot-scope="scope">
          <span>{{ scope.row.course_name }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="作业状态" width="110">
        <template slot-scope="{ row }">
          <el-tag :type="judgestatus(row) | statusFilter">
            {{ judgestatus(row) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="发布状态" width="110">
        <template slot-scope="{ row }">
          <el-tag :type="row.assignment_status | statusFilter">
            {{ row.assignment_status == 'published' ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="200px" label="作业名称">
        <template slot-scope="{ row }">
          <router-link
            :to="'/home/edit/' + row.assignment_id"
            class="link-type"
          >
            <span>{{ row.assignment_title }}</span>
          </router-link>
          <el-tag style="margin-left: 10px">{{ row.total_points }}分</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <router-link :to="'/home/edit/' + row.assignment_id">
            <el-button type="primary" size="mini"> 编辑 </el-button>
          </router-link>
          <el-button
            style="margin-left: 10px"
            v-if="row.assignment_status != 'published'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row, 'published')"
          >
            发布
          </el-button>
          <el-button
            style="margin-left: 10px"
            v-if="row.assignment_status != 'draft'"
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            草稿
          </el-button>
          <el-button
            v-if="row.assignment_status != 'deleted'"
            size="mini"
            type="danger"
            @click="open(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import waves from "@/directive/waves"; // waves directive
import UserAcatar from "@/components/UserAcatar.vue"; //引入组件
// import { parseTime } from '@/utils'
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "ComplexTable",
  components: { Pagination, UserAcatar },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
        '已截止': "danger",
        "进行中": "success",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        type: undefined,
        sort: "+id",
      },
      importanceOptions: [1, 2, 3],
      // calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      userInfo: {},
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },
  created() {
    this.userInfo = JSON.parse(JSON.stringify(this.$store.state.user_info));
    console.log(this.userInfo);
    this.getList();
    console.log(123456);
  },
  methods: {
    judgestatus(row) {
      console.log(row);
      console.log(Date.now(), new Date(row.deadline).getTime(), new Date(row.publish_time).getTime());
      if(new Date(row.publish_time).getTime() < Date.now() && new Date(row.deadline).getTime() > Date.now()) {
        console.log(1);
        return "进行中"
      } else if(Date.now() < new Date(row.publish_time).getTime()) {
        console.log(2);
        return "未开始"
      } else if (Date.now() > new Date(row.deadline).getTime()) {
        console.log(3);
        return "已截止"
      }
    },
    // 将头像组件中的路由再传递给homeview
    change(msg) {
      this.$emit("transfer", msg);
    },
    async open(row, index) {
      this.$confirm("此操作将永久删除该作业, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(row);
          let response = await this.$axios.post("/assignment/deleteAssignment", { id: row.assignment_id })
          if (response.code == 200) {
            this.$notify({
              title: "Success",
              message: "Delete Successfully",
              type: "success",
              duration: 2000,
            });
            this.getList();
          }
          this.list.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getList() {
      this.listLoading = true;
      let response = await this.$axios.get('/assignment/getAssignment', {params: {teacher_id: this.userInfo.teacher_id, pageNum: this.listQuery.page,
        pageSize: this.listQuery.limit,}})

        if(response.code == 200) {
          setTimeout(() => {
            this.listLoading = false;
          }, 0.5 * 100);
          setTimeout(() => {
            console.log(response);
            console.log(response.data);
            this.list = response.data;
            this.total = response.total;
          }, 0.5 * 100);
        }
        // Just to simulate the time of the request
      
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    async handleModifyStatus(row, status) {
      console.log(row);
      let response = await this.$axios('/assignment/changeStatus', { id: row.assignment_id, status });
      if (response.code == 200) {
        this.$message({
          message: "操作Success",
          type: "success",
        });
        row.assignment_status = status;
      }
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    handleCreate() {
      // this.resetTemp()
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.$router.push("publishjob");
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      //   })
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>

<style lang="scss" scoped>
.header {
  padding-top: 10px;
  padding-bottom: 10px;
  display: flex;
  justify-content: flex-end;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}
.link-type,
.link-type:focus {
  color: #337ab7;
  cursor: pointer;

  &:hover {
    color: rgb(32, 160, 255);
  }
}
</style>
